package watcher

import (
	"github.com/shirou/gopsutil/cpu"
	"github.com/sirupsen/logrus"
	"time"
	"watcher/client/config"
)

type CpuWatcher struct {
	logger   logrus.Logger
	Done     chan struct{}
	Duration time.Duration
}

func (watcher *CpuWatcher) Watch() <-chan *WatchData {
	dataChan := make(chan *WatchData, 10)
	go watcher.watch(dataChan, watcher.Duration)
	return dataChan
}

func (watcher *CpuWatcher) watch(c chan<- *WatchData, interval time.Duration) {
	defer close(c)
	for {
		select {
		case <-watcher.Done:
			break
		default:
			func() {
				f, err := cpu.Percent(interval, false)
				if err != nil {
					return
				}
				c <- &WatchData{
					Measurement: "cpu",
					Time:        time.Now(),
					Fields: map[string]interface{}{
						"percent": f[0],
					},
				}
			}()
		}
	}
}

func (watcher *CpuWatcher) Close() {
	close(watcher.Done)
}

func NewCpuWatcher(conf config.Conf) (*CpuWatcher, error) {
	return &CpuWatcher{
		Done:     make(chan struct{}),
		Duration: conf.Duration,
	}, nil
}

var CpuRegister = func(conf config.Conf) (string, Watcher, error) {
	w, err := NewCpuWatcher(conf)
	return "cpu", w, err
}
